import 'dart:io';

import 'package:my_soft/configs/api.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeLogic extends GetxController with GetSingleTickerProviderStateMixin {
  List appListBackup = [];

  RxList appList = RxList();
  RxDouble process = RxDouble(0.0);
  RxBool processShow = RxBool(false);

  late TabController tabController;
  late TextEditingController searchCtrl;
  FocusNode textFocus1 = FocusNode();
  ScrollController scrollController = ScrollController();

  final List<Tab> myTabs = <Tab>[
    const Tab(text: '全部软件'),
    const Tab(text: '安卓'),
    const Tab(text: 'Windows'),
    const Tab(text: 'Linux'),
  ];
//判断是否有权限
  void checkPermission() async {
    Permission permission = Permission.locationAlways;
    PermissionStatus status = await permission.status;
    debugPrint('检测权限-->$status');
    if (status.isGranted) {
      //权限通过
    } else if (status.isDenied) {
      //权限拒绝， 需要区分IOS和Android，二者不一样
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示，需要进入设置界面
      openAppSettings();
    } else if (status.isRestricted) {
      //活动限制（例如，设置了家长///控件，仅在iOS以上受支持。
      openAppSettings();
    } else {
      //第一次申请
      requestPermission(permission);
    }
  }

  //申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    debugPrint('权限状态$status');
    if (!status.isGranted) {
      openAppSettings();
    }
  }

  @override
  void onInit() {
    // checkPermission();
    // Api.initurl();
    super.onInit();
    searchCtrl = TextEditingController();
    tabController = TabController(vsync: this, length: myTabs.length);
    tabController.addListener(() => listenerTab());
    Api.getAppList().then((v) {
      appList.value = v;
      appListBackup = v;
    });
    // 每次 监听
    ever(process, (value) {
      debugPrint("进度--->$value");
      if (value >= 0.99 || value == 0.0) {
        processShow.value = false;
      } else {
        processShow.value = true;
      }
    });
    // 原生调用
  }

  @override
  void onClose() {
    super.onClose();
    tabController.dispose();
  }

  RegExp re = RegExp(r"\.(\w+)\?");
  downloadFlie(String filename, url) async {
    // todo-----
    String lzUrl = await Api.getlanzouzl(url);
    debugPrint("解析后-->$lzUrl");
    late String storagePath;
    if (Platform.isAndroid) {
      // downloadsDir = await getExternalStorageDirectory();
      storagePath = "/storage/emulated/0/Download";
    } else {
      Directory? downloadsDir = await getDownloadsDirectory();
      storagePath = downloadsDir!.path;
    }

    final type = re.firstMatch(lzUrl);
    File file = File('$storagePath/${filename.trim()}.${type![1]}');

    // \.(\w+)\?
    debugPrint("保存->${file.path}");

    // if (!file.existsSync()) {
    //   file.createSync();
    // }

    /// dio使用get下载文件
    try {
      var response = await Dio().download(
        lzUrl,
        file.path,
        onReceiveProgress: (num received, num total) {
          /// 获取下载进度
          double downloadprocess = double.parse((received / total).toStringAsFixed(2));
          // debugPrint("下载进度->${process * 100}");
          process.value = downloadprocess;
        },
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
        ),
      );
      // file.writeAsBytesSync(response.data);
      /// 写入文件
      // return file;
    } catch (e) {
      checkPermission();
      debugPrint("下载文件报错: ${e.toString()}");
    }
  }

  // tab切换函数
  listenerTab() {
    //避免addListener调用2次
    if (tabController.index == tabController.animation?.value) {
      switch (tabController.index) {
        case 0:
          appList.value = List.from(appListBackup);
        case 1:
          appList.value = List.from(appListBackup);
          appList.removeWhere((e) => e['类型'] != "安卓");
        case 2:
          appList.value = List.from(appListBackup);
          appList.removeWhere((e) => e['类型'] != "Windows");
        case 3:
          appList.value = List.from(appListBackup);
          appList.removeWhere((e) => e['类型'] != "Linux");
      }
    }
  }

  // 搜索框 过滤
  searchcompleter() {
    textFocus1.unfocus();
    appList.value = List.from(appListBackup);
    // 简介 (和) 名称 带有 搜索词
    appList.removeWhere((e) => !e['简介'].toString().contains(searchCtrl.text) && !e['name_all'].toString().contains(searchCtrl.text));
  }
}
